/**
 * 统一错误处理包装器
 * 为前端API调用提供统一的错误处理、重试机制和可观测性
 */

import { message } from 'antd';
import { getErrorMessage, getHttpErrorMessage, ERROR_TYPES } from '../utils/i18n';

// 错误类型定义
export const ERROR_CATEGORIES = {
  NETWORK: 'NETWORK',
  VALIDATION: 'VALIDATION', 
  AUTHORIZATION: 'AUTHORIZATION',
  SERVER: 'SERVER',
  TIMEOUT: 'TIMEOUT',
  UNKNOWN: 'UNKNOWN'
};

// 错误日志收集器
class ErrorLogger {
  constructor() {
    this.errors = [];
    this.maxErrors = 100; // 最多保存100个错误
  }

  log(error, context = {}) {
    const errorEntry = {
      timestamp: new Date().toISOString(),
      message: error.message,
      stack: error.stack,
      category: this.categorizeError(error),
      context,
      url: window.location.href,
      userAgent: navigator.userAgent
    };

    this.errors.unshift(errorEntry);
    if (this.errors.length > this.maxErrors) {
      this.errors.pop();
    }

    // 发送到控制台用于调试
    console.error('[ErrorLogger]', errorEntry);
    
    // 可选：发送到监控服务
    this.sendToMonitoring(errorEntry);
  }

  categorizeError(error) {
    if (error.code === 'NETWORK_ERROR' || error.message.includes('Network')) {
      return ERROR_CATEGORIES.NETWORK;
    }
    if (error.response?.status === 401 || error.response?.status === 403) {
      return ERROR_CATEGORIES.AUTHORIZATION;
    }
    if (error.response?.status >= 400 && error.response?.status < 500) {
      return ERROR_CATEGORIES.VALIDATION;
    }
    if (error.response?.status >= 500) {
      return ERROR_CATEGORIES.SERVER;
    }
    if (error.code === 'TIMEOUT') {
      return ERROR_CATEGORIES.TIMEOUT;
    }
    return ERROR_CATEGORIES.UNKNOWN;
  }

  sendToMonitoring(errorEntry) {
    // 这里可以集成第三方监控服务如Sentry、LogRocket等
    // 目前只是存储到localStorage用于调试
    try {
      const existingErrors = JSON.parse(localStorage.getItem('app_errors') || '[]');
      existingErrors.unshift(errorEntry);
      // 只保存最近50个错误到localStorage
      localStorage.setItem('app_errors', JSON.stringify(existingErrors.slice(0, 50)));
    } catch (e) {
      console.warn('Failed to save error to localStorage:', e);
    }
  }

  getErrors() {
    return this.errors;
  }

  clearErrors() {
    this.errors = [];
    localStorage.removeItem('app_errors');
  }
}

// 全局错误日志实例
export const errorLogger = new ErrorLogger();

// 重试配置
const RETRY_CONFIG = {
  maxRetries: 3,
  retryDelay: 1000, // 1秒
  retryMultiplier: 2, // 指数退避
  retryableErrors: [408, 429, 500, 502, 503, 504]
};

// 延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// API包装器类
export class ApiWrapper {
  constructor(axiosInstance, options = {}) {
    this.axios = axiosInstance;
    this.options = {
      enableRetry: true,
      enableLogging: true,
      showUserMessages: true,
      ...options
    };
  }

  async request(config, context = {}) {
    const { enableRetry, enableLogging, showUserMessages } = this.options;
    let lastError;
    let retryCount = 0;

    while (retryCount <= RETRY_CONFIG.maxRetries) {
      try {
        const response = await this.axios(config);
        
        // 成功时清除之前的错误状态
        if (retryCount > 0 && showUserMessages) {
          message.success('网络连接已恢复');
        }
        
        return response;
      } catch (error) {
        lastError = error;
        
        if (enableLogging) {
          errorLogger.log(error, { ...context, config, retryCount });
        }

        // 检查是否应该重试
        if (!enableRetry || !this.shouldRetry(error, retryCount)) {
          break;
        }

        retryCount++;
        const delayMs = RETRY_CONFIG.retryDelay * Math.pow(RETRY_CONFIG.retryMultiplier, retryCount - 1);
        
        if (showUserMessages && retryCount === 1) {
          message.warning(`网络请求失败，正在重试... (${retryCount}/${RETRY_CONFIG.maxRetries})`);
        }
        
        await delay(delayMs);
      }
    }

    // 所有重试都失败了，处理最终错误
    this.handleFinalError(lastError, context, showUserMessages);
    throw lastError;
  }

  shouldRetry(error, retryCount) {
    if (retryCount >= RETRY_CONFIG.maxRetries) {
      return false;
    }

    // 网络错误总是重试
    if (!error.response) {
      return true;
    }

    // 检查状态码是否可重试
    return RETRY_CONFIG.retryableErrors.includes(error.response.status);
  }

  handleFinalError(error, context, showUserMessages) {
    if (!showUserMessages) return;

    const { page } = context;
    let errorMessage;

    if (!error.response) {
      // 网络错误
      errorMessage = '网络连接异常，请检查网络设置';
    } else {
      // HTTP错误
      const status = error.response.status;
      if (page && ERROR_TYPES.LOAD_FAILED) {
        errorMessage = getErrorMessage(page, ERROR_TYPES.LOAD_FAILED);
      } else {
        errorMessage = getHttpErrorMessage(status);
      }
    }

    message.error(errorMessage);
  }

  // 便捷方法
  get(url, config = {}, context = {}) {
    return this.request({ ...config, method: 'GET', url }, context);
  }

  post(url, data, config = {}, context = {}) {
    return this.request({ ...config, method: 'POST', url, data }, context);
  }

  put(url, data, config = {}, context = {}) {
    return this.request({ ...config, method: 'PUT', url, data }, context);
  }

  delete(url, config = {}, context = {}) {
    return this.request({ ...config, method: 'DELETE', url }, context);
  }
}

// 输入校验工具
export class InputValidator {
  static validateDateRange(startDate, endDate) {
    const errors = [];
    
    if (!startDate || !endDate) {
      errors.push('请选择完整的日期范围');
      return errors;
    }

    if (startDate.isAfter(endDate)) {
      errors.push('开始日期不能晚于结束日期');
    }

    const daysDiff = endDate.diff(startDate, 'days');
    if (daysDiff > 365) {
      errors.push('日期范围不能超过365天');
    }

    return errors;
  }

  static validateCouponForm(formData) {
    const errors = [];
    
    if (!formData.name?.trim()) {
      errors.push('优惠券名称不能为空');
    }
    
    if (!formData.code?.trim()) {
      errors.push('优惠券代码不能为空');
    } else if (!/^[A-Z0-9]{4,20}$/.test(formData.code)) {
      errors.push('优惠券代码只能包含大写字母和数字，长度4-20位');
    }
    
    if (!formData.type) {
      errors.push('请选择优惠券类型');
    }
    
    if (formData.value <= 0) {
      errors.push('优惠值必须大于0');
    }
    
    if (formData.type === 'discount' && formData.value > 100) {
      errors.push('折扣券的优惠值不能超过100%');
    }
    
    if (formData.minAmount < 0) {
      errors.push('最低消费金额不能为负数');
    }
    
    if (formData.totalCount <= 0) {
      errors.push('发放数量必须大于0');
    }
    
    return errors;
  }

  static validateMenuForm(formData) {
    const errors = [];
    
    if (!formData.name?.trim()) {
      errors.push('菜品名称不能为空');
    }
    
    if (formData.price <= 0) {
      errors.push('菜品价格必须大于0');
    }
    
    if (formData.price > 9999) {
      errors.push('菜品价格不能超过9999元');
    }
    
    if (!formData.category?.trim()) {
      errors.push('请选择菜品分类');
    }
    
    return errors;
  }
}

// 使用示例和最佳实践
export const USAGE_EXAMPLES = {
  // 在组件中使用ApiWrapper
  component: `
// 在组件中使用
import { ApiWrapper } from './error-handling-wrapper';
import api from '../utils/api';

const apiWrapper = new ApiWrapper(api, {
  enableRetry: true,
  enableLogging: true,
  showUserMessages: true
});

// 在报表组件中
const fetchReportData = async () => {
  try {
    const response = await apiWrapper.get(
      \`/reports/\${reportKey}\`,
      { params },
      { page: 'REPORTS' }
    );
    setReportData(response.data);
  } catch (error) {
    // 错误已经被wrapper处理，这里只需要处理UI状态
    setError(true);
  }
};
  `,
  
  // 输入校验使用
  validation: `
// 在表单提交前校验
const handleSubmit = () => {
  const errors = InputValidator.validateCouponForm(formData);
  if (errors.length > 0) {
    message.error(errors[0]);
    return;
  }
  // 继续提交逻辑
};
  `
};